// pageB/pages/look/look.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sel_id:'',
    navid:null,
    token:'',
    openid:'',
    user_id:'',
    OrderMessage:[],
    cateList:['待支付','待使用','待评价','已评价','已取消'],
    arr:[],
    roomMessage:[],
    arr2:[],
    arr3:[],
    timeLeft: '30:00',  // 初始显示 30 分钟
  },

  getuserinfo:function () { 
    var that =this
    wx.request({
      url: `http://hotel.ttt:3007/protected/getuserinfo/${this.data.openid}`,
      method:'GET',
      header:{
        'Authorization': that.data.token 
      },
      success(res) {
        that.setData({
          user_id:res.data.data[0].user_id
        })
        console.log(that.data.navid);
        if(that.data.navid===0){
          that.setData({roomMessage:[]})
          that.getallOrderMessage(res.data.data[0].user_id,"pending","confirmed")
        }
        else if (that.data.navid===1){
          that.setData({roomMessage:[]})
          that.getallOrderMessage(res.data.data[0].user_id,"paid","confirmed")
        }
        else if(that.data.navid===2){
          that.setData({roomMessage:[]})
          that.getallOrderMessage(res.data.data[0].user_id,"paid","completed")
        }
        else if(that.data.navid===3){
          that.setData({roomMessage:[]})
          that.getallOrderMessage(res.data.data[0].user_id,"paid","commented")}
        else {
          that.setData({roomMessage:[]})
          that.getallOrderMessage(res.data.data[0].user_id,'failed','cancelled')
        }
      }
    })
  },
  getallOrderMessage:function(user_id,payment_status,order_status){
    var that=this 
    console.log(user_id,payment_status,order_status);
    wx.request({
      url: 'http://hotel.ttt:3007/protected/allorderMessage',
      method: 'post',  // 请求方法是 GET
      header:{
        'Authorization': that.data.token// 将 token 添加到请求头
      },
      data:{
        user_id,payment_status,order_status
      },
      success: function (res) {
        console.log(res.data.data)
        that.setData({
          OrderMessage:res.data.data 
        })
        let arr = [];
        let arr2=[];
        let arr3=[]
        that.data.OrderMessage.forEach(e => { 
          arr.push(e.total_price)
          arr2.push(e.order_id)
          arr3.push(that.convertToChinaTime(e.check_in_date).substring(0,10),that.convertToChinaTime(e.check_out_date).substring(0,10))
        })
        that.setData({
          arr,arr2,arr3
        })
        if(that.data.OrderMessage.length===0){
          that.setData({
            roomMessage:[]
          })
        }
        for(var i=0;i<that.data.OrderMessage.length;i++){
          that.getRoomMessage(res.data.data[i].room_id)
        }
      },
      fail: function (err) {
        console.error('请求失败:', err);
      }
    })
  },
  getPaymentMessage:function(){
    var that=this
    wx.request({
      url: `http://hotel.ttt:3007/protected/paymentMessage/${that.data.order_id}`,
      method:'get',
      header:{
        'Authorization': that.data.token// 将 token 添加到请求头
      },
      success:function(res){
        if(res.data.success){
          console.log('订单支付查询成功',res.data.data[0])
          wx.setNavigationBarTitle({
            title: `订单: ${res.data.data[0].transaction_id.substring(25, 40)}`
          });
          that.setData({
            PaymentMessage:res.data.data[0],
            transaction_id:res.data.data[0].transaction_id.substring(25, 40)
          })
        }else{console.log(res.data);}
      },
      fail(err) {
        console.error('失败', err);
      }
    })
  },
  getRoomMessage:function(e){
    var that =this
    wx.request({
      url: `http://hotel.ttt:3007/protected/roomMessage/${e}`,
      method:'GET',
      header:{
        'Authorization': that.data.token// 将 token 添加到请求头
      },
      success:function(res){
        if(res.data.success){
          const roomMessage = [...that.data.roomMessage, res.data.data[0]]; 
          that.setData({
            roomMessage
          })
        }else{
          console.log('查询失败',res.data)
        }
      },
      fail:function(err){
        console.log(err);
      }
    })
  },
  onNavigate:function(e){
    if(Number.isInteger(e)){
      this.setData({
        navid:e
      })
    }else{
      this.setData({
      navid:e.currentTarget.dataset.navid
    })
    console.log('navid=',e.currentTarget.dataset.navid)
    if(this.data.navid===0){
      this.startCountdown();  // 页面加载时启动倒计时
    }
  }
    this.getuserinfo()
  },

  startCountdown() {  // 启动倒计时
    if (this.data.timer || this.data.timeLeft > 0) {
      // 如果已有定时器在运行，或者 timeLeft 不为 0，返回
      return;
    }
    let time = 30 * 60; // 30 分钟转化为秒数
    this.setData({ timeLeft: this.formatTime(time) });  // 设置初始时间显示

    // 每秒更新一次倒计时
    const timer = setInterval(() => {
      time--;  // 每次减少 1 秒
      this.setData({ timeLeft: this.formatTime(time) });  // 更新显示

      if (time <= 0) {
        clearInterval(timer);  // 倒计时结束，清除定时器
        this.cancel();  // 倒计时结束，执行函数
      }
    }, 1000);

    this.setData({ timer: timer });  // 保存定时器 ID
  },
  formatTime(seconds) { // 格式化时间：秒数 -> "mm:ss" 格式
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${this.padZero(minutes)}:${this.padZero(remainingSeconds)}`;
},
padZero:function(num) {  // 补零函数，确保两位数格式
  return num < 10 ? '0' + num : num;
},
cancel:function(e){
  var that =this
  console.log(e.currentTarget.dataset.id)
   wx.request({
    url: 'http://hotel.ttt:3007/protected/usedOrder',
    method: 'post',  // 请求方法是 GET
    header:{
      'Authorization': that.data.token// 将 token 添加到请求头
    },
    data:{
      payment_status:'failed',
      order_status:'cancelled',
       order_id:e.currentTarget.dataset.id
    },
    success: function (res) {
      that.updatePaymentStatus('failed',e.currentTarget.dataset.id)
      console.log(res.data.message,'that.data.user_id',that.data.user_id)
      that.getallOrderMessage(that.data.user_id,"pending","confirmed")
    },
    fail: function (err) {
      console.error('请求失败:', err);
    }
  }) 
},
updatePaymentStatus:function(status,orderid){
  wx.request({
    url: `http://hotel.ttt:3007/protected/usedPayment/${status}/${orderid}`,
    method:'POST',
    header:{
      'Authorization': this.data.token// 将 token 添加到请求头
    },
    success: function (res) {
      if(res.data.success)console.log(res.data.message)
      else console.log('更新状态失败',res.data)
    },
    fail: function (err) {
      console.error('请求失败:', err);
    }
  })
},
gotopay:function(e){
  console.log(e.currentTarget.dataset.money,e.currentTarget.dataset.orderid,e.currentTarget.dataset.roomid)
  var that = this
  wx.showModal({
    title: '提示',  // 弹窗的标题
    content: `请支付房费￥${e.currentTarget.dataset.money}`,  // 弹窗的内容
    showCancel: true,  // 是否显示取消按钮，默认为 true
    cancelText: '取消',  // 取消按钮的文字
    confirmText: '支付',  // 确定按钮的文字
    success(res) {
      if (res.confirm) {
        // 用户点击了确定
        console.log('用户点击了确定');
        that.wxpay(e.currentTarget.dataset.orderid)
        that.updataRoomStatus('booked',e.currentTarget.dataset.roomid)
        // 使用 setTimeout 实现2秒后跳转
        wx.showLoading({
          title: '加载中...',
          mask: true // 遮罩层，防止用户点击其它区域
        });
        setTimeout(() => {
          wx.hideLoading();// 隐藏 loading 提示框 
        }, 2000);
        } else if (res.cancel) {
          // 用户点击了取消
          console.log('用户点击了取消');
        }
    },fail(err) {
      // 弹窗调用失败时的回调
      console.error('弹窗失败', err);
    }
    }) 
},
wxpay:function(orderid){
  var that=this 
  wx.request({
    url: 'http://hotel.ttt:3007/protected/usedOrder',
    method: 'post',  // 请求方法是 GET
    header:{
      'Authorization': that.data.token// 将 token 添加到请求头
    },
    data:{
      payment_status:'paid',
      order_status:'confirmed',
      order_id:orderid
    },
    success: function (res) {
      console.log(res.data.message)
      that.updatePaymentStatus('successful',orderid)

    },
    fail: function (err) {
      console.error('请求失败:', err);
    }
  })
},
updataRoomStatus:function(e,roomid){
  wx.request({
    url: `http://hotel.ttt:3007/api/usedRoom/${e}/${roomid}`,
    method: 'post',  // 请求方法是 GET
    success:function(res){
      if(res.data.success) console.log('更新房间状态成功');
      else console.log('更新房间状态失败');
    },fail:function(err){
      console.log(err);
    }
  })
},
gotocomment:function(e){
  wx.navigateTo({
    url: '/pageB/pages/comment/comment?room_id='+e.currentTarget.dataset.room_id+'&user_id='+e.currentTarget.dataset.user_id+'&order_id='+e.currentTarget.dataset.order_id+'&name='+e.currentTarget.dataset.name,
  }) 
},

// 自定义函数：将 UTC 时间转为中国时间（UTC+8）
convertToChinaTime:function(utcTime) {
  const date = new Date(utcTime);
  date.setHours(date.getHours()); // 调整时区为 UTC+8（中国标准时间）
  return this.formatDate(date);
},
// 格式化日期函数：将 Date 对象格式化为 'YYYY-MM-DD HH:mm:ss' 格式
formatDate:function(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const token =wx.getStorageSync('token')
    const openid =wx.getStorageSync('openid')
    this.setData({
      sel_id:options.id,
      navid:parseInt(options.id),
      token,
      openid
    })
    this.onNavigate(parseInt(options.id))
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})